const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 用户注册
router.post('/register', async (req, res) => {
    try {
        const { username, password } = req.body;

        // 检查用户是否已存在
        const [users] = await db.execute(
            'SELECT * FROM users WHERE username = ?',
            [username]
        );

        if (users.length > 0) {
            return res.status(400).json({ message: '用户名已存在' });
        }

        // 插入新用户
        await db.execute(
            'INSERT INTO users (username, password) VALUES (?, ?)',
            [username, password]  // 注意：实际应用中应该对密码进行加密
        );

        res.status(201).json({ message: '注册成功' });
    } catch (error) {
        console.error('注册错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 用户登录
router.post('/login', async (req, res) => {
    try {
        const { username, password } = req.body;

        // 查询用户
        const [users] = await db.execute(
            'SELECT * FROM users WHERE username = ? AND password = ?',
            [username, password]  // 注意：实际应用中应该对密码进行加密比对
        );

        if (users.length === 0) {
            return res.status(401).json({ message: '用户名或密码错误' });
        }

        res.json({ message: '登录成功', user: { username: users[0].username } });
    } catch (error) {
        console.error('登录错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

module.exports = router; 